package com.ancy.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.ancy.aynch.LoginTask;
import com.ancy.backupandroid.R;
import com.ancy.common.IError;

public class LoginActivity extends Activity implements IError {

	RelativeLayout progressLayout;
	EditText usernameText;
	EditText passwordText;
	Button loginButton;
	Button signupButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initializeUI();
		setClickListeners();
	}

	void initializeUI() {
		progressLayout = (RelativeLayout) findViewById(R.id.progress_login_layout);
		usernameText = (EditText) findViewById(R.id.txtUsername);
		passwordText = (EditText) findViewById(R.id.txtPassword);
		loginButton = (Button) findViewById(R.id.btnLogin);
		signupButton = (Button) findViewById(R.id.btnSignUp);
	}

	void setClickListeners() {
		loginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				doLogin();
			}
		});

		signupButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(),
						RegisterActivity.class);
				startActivity(intent);
			}
		});
	}

	void doLogin() {
		if (doValidate()) {
			LoginTask task = new LoginTask(usernameText.getText().toString()
					.trim(), passwordText.getText().toString(), progressLayout,
					this);
			task.execute();
		}
	}

	boolean doValidate() {

		if (usernameText.getText().toString().trim().equals("")) {
			Toast.makeText(getApplicationContext(), USERNAME_REQ,
					Toast.LENGTH_SHORT).show();
			return false;
		} else if (passwordText.getText().toString().trim().equals("")) {
			Toast.makeText(getApplicationContext(), PASSWD_REQ,
					Toast.LENGTH_SHORT).show();
			return false;
		}

		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}
